qui(
    function (require, exports, module) {
        live2VOD.Edit = function (options) {
            this.dao = live2VOD.Dao;
            this.config = live2VOD.Config;
            this.options = options || {};
        };
        Com.inherits(live2VOD.Edit, Ancestor.Grid).extend({
            init: function () {
                var self = this;
                self.initSuggest();
                self.fillForm();
                self.bindBasicEvent();
            },
            fillForm: function () {
                var channeltype = decodeURIComponent(live2VOD.Util.getUrlId("channeltype"));
                var channelalias = live2VOD.Util.getUrlId("channelalias");
                var self = this;
                if (channeltype != null && channelalias != null) {
                    self.dao.getList({channeltype: channeltype, channelalias: channelalias, pageNo: 0, pageSize: 1000 }, function (data) {
                        var retValue = null;
                        self.config.PageBean = live2VOD.Util.createPageBean();
                        if (data.code === 200 && data.response != null && data.response.data != null) {
                            self.config.PageBean.setNewData(data.response.data, self.config.TABLE_LIST.rowNum);
                        } else {
                            self.config.PageBean.setNewData([], self.config.TABLE_LIST.rowNum);
                        }
                        retValue = self.config.PageBean.getCur();
                        if (retValue.rows.length > 0) {
                            self.fillData(retValue.rows[0]);
                        } else {
                            self.fillNoData();
                        }
                    });
                } else {
                    self.fillNoData();
                }
                self.options.$form.find("input[name=ptype]").val("UGC");
                self.options.$form.find("input[name=ptype]").attr("disabled", "disabled");
            },
            fillData: function (element) {
                var self = this;
                //var selectDom = self.options.$form.find("select[name=channeltype]");
                //self.dao.getChannelType(function (data) {
                //    $.each(data, function (i, element) {
                //        $("<option>", {
                //            value: element.value,
                //            html: element.value
                //        }).appendTo(selectDom);
                //    });


                //});
                for (var key in element) {
                    if (key == "channeltype") {
                        var rule = /[\u4E00-\u9FA5a-zA-Z0-9]+/g;
                        var channeltype = element[key];
                        var jsonArray = channeltype.match(rule);
                        $.each(jsonArray, function (i, data) {
                            var tag_span = $('<span class="ui-suggest-value tagmanagerTag" data-tag-label="' + data + '">' + data + '<a class="tagmanagerRemoveTag"  onclick="$(this).parent().remove();"  title="Remove" href="javascript:;">x</a></span>');
                            $("#channeltype-val").append(tag_span);
                            if (i == 0) {
                                //self.options.$form.find("option[value=" + data + "]").attr('selected', true);
                                //$("option[value=" + data + "]").attr('selected', true);
                                //selectDom.val(data);
                            }
                        });
                    } else {
                        self.options.$form.find("input[name=" + key + "]").val(element[key]);
                    }
                }
                //self.options.$form.find("select[name=channeltype]").attr("disabled", "disabled");
                self.options.$form.find("input[name=ptype]").attr("disabled", "disabled");
                self.options.$form.find("input[name=channelalias]").attr("disabled", "disabled");
            },
            fillNoData: function () {
                var self = this;
                //self.dao.getChannelType(function (data) {
                //    var selectDom = self.options.$form.find("select[name=channeltype]");
                //    $.each(data, function (i, element) {
                //        $("<option>", {
                //            value: element.value,
                //            html: element.value
                //        }).appendTo(selectDom);
                //    })
                //});
            },
            getParam: function () {
                var self = this;
                var params = {};
                var $form = self.options.$form;
                var $elements = $.makeArray($form.prop('elements')).filter(function () {
                    return true; //this.name;
                });
                $.each($elements, function (i, element) {
                    if (element.type == "button") {
                        return true;
                    }
                    if (element.name == "channeltype") {
                        var channeltypeJson;
                        var channeltypes = $("#channeltype-val").find("span.ui-suggest-value");
                        if (channeltypes.length <= 0) {

                        } else {
                            for (i=0; i<channeltypes.length; i++) {
                                if (i == 0) {
                                    channeltypeJson = '[';
                                }
                                var channeltype = $(channeltypes[i]).attr("data-tag-label");
                                channeltypeJson = channeltypeJson + '"' + channeltype + '"';
                                if (i == channeltypes.length-1) {
                                    channeltypeJson = channeltypeJson + ']';
                                } else {
                                    channeltypeJson = channeltypeJson + ',';
                                }
                            }
                        }
                        params["channeltype"] = channeltypeJson;
                        return true;
                    }
                    params[element.name] = $(element).val();
                })
                    if (self.config.PageBean != null) {
                    var dataArr = self.config.PageBean.getCur().rows;
                    if (dataArr.length > 0) {
                        params["srcchannelalias"] = dataArr[0].channelalias;
                        params["srcchanneltype"] = dataArr[0].channeltype;
                    }
                }
                return params;
            },
            bindBasicEvent: function () {
                var self = this;
                $("button[name=commitBtn]").bind("click", function (event) {
                    if (! self.$validator.form()){
                        console.log("验证失败");
                        return;
                    }
                    var params = self.getParam()
                    if (params["channeltype"] == null) {
                        SystemDialog.queryAlert("频道类型为空，提交失败!");
                        return;
                    }
                    if (self.config.PageBean != null) {
                        live2VOD.Util.modifyChannel(self.getParam())
                    } else {
                        live2VOD.Util.addChannel(self.getParam())
                    }
                })
                $.validator.addMethod("selfReg",function(value,element,params){
                    return params.test(value);
                },"需要大写字母或阿拉伯数字")
                self.$validator =  live2VOD.Util.getValidator(self.options.$form, self.config.EDIT_VALIDATOR);

                $("#channeltype").on('change', function() {
                    var val = $(this).find("option:selected").text();
                    var channeltypes = $("#channeltype-val").find("span");
                    var flag = true;
                    for (i=0; i<channeltypes.length; i++) {
                        var channeltype = $(channeltypes[i]).attr("data-tag-label");
                        if (val == channeltype) {
                            flag = false;
                            break;
                        }
                    }
                    if (flag) {
                        var tag_span = $('<span class="ui-suggest-value tagmanagerTag" data-tag-label="' + val + '">' + val + '<a class="tagmanagerRemoveTag"  onclick="$(this).parent().remove();"  title="Remove" href="javascript:;">x</a></span>');
                        $("#channeltype-val").append(tag_span);
                    }
                });
            },
            initSuggest: function () {
                var self = this;
                var channelTypeSuggest = {
                    options: {
                        source: EpgWeb.urlConfig.redirect,
                        renderPanel: function (handler) {
                            self.dao.getChannelType(handler)
                        },
                        method: "post",
                        multiple: true,
                        parseValue: function () {
                            var val = this.element.val(),
                                ret = []
                            return ret;
                        },
                        getParam: function (term) {
                            var params = term.length == 0 ? {size: 100} : {word: term, size: 100}
                            var requestData = {url: live2VOD.Constant.thirdUrl_channel_type, type: "get", params: params, needCookie: true};
                            return {"request": JSON.stringify(requestData), timeSign: new Date().getTime()}
                        },

                        process: function (json) {
                            var ret = [],
                                self = this,
                                options = self.options,
                                itemData = null;
                            var data = null;
                            if (json == null) {
                                return [];
                            }
                            if (json.code === "A00000") {
                                data = $.isArray(json) ? json : json.data;
                            }
                            if (!data) {
                                return [];
                            }
                            $.map(data, function (item) {
                                itemData = {};
                                itemData[options.valueKey] = item["id"];
                                itemData[options.labelKey] = item["name"];
                                itemData["value"] = item["name"];
                                ret.push(itemData);
                            });
                            return ret;
                        },

                        template: function (item) {
                            return item["label"];
                        }
                    }
                }
                $("input[name=channeltype]").suggest(channelTypeSuggest.options);
                $("input[name=channeltype]").suggest("setSelectedItem", null);
            }
        })
    }
);